//
//  ICResertPasswardViewController_1.m
//  ICome
//
//  Created by zhangrongwu on 16/7/14.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICEditPasswardViewController.h"
#import "ZYKeyboardUtil.h"
#import "ICLoginNetworkManager.h"
#import "ICHeaderFile.h"

@interface ICEditPasswardViewController()<UITextFieldDelegate>

@property (strong, nonatomic)ZYKeyboardUtil *keyboardUtil;
@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, strong)UILabel *titleLabel;
@property (nonatomic, strong)UILabel *phoneLabel;
@property (nonatomic, strong)UITextField *safetyCodeTextField;
@property (nonatomic, strong)UITextField *passwardTextField;
@property (nonatomic, strong)UITextField *rePasswardTextField;
@property (nonatomic, strong)UILabel *timeLabel;
@property (nonatomic, strong)UIButton *finishButton;
@property (nonatomic, strong)NSTimer *timer; //倒计时
@property (nonatomic, strong)UIView *bottomView;
@property (nonatomic, strong)UIView *bottomView_1;
@property (nonatomic, strong)UIView *bottomView_2;
@property (nonatomic, strong)UIView *topView;

@property (nonatomic, strong)UIButton *passwdStatusButton;
@property (nonatomic, strong)UIButton *repasswdStatusButton;


@end
@implementation ICEditPasswardViewController
#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setNav];
    
    WEAKSELF;
    self.keyboardUtil = [[ZYKeyboardUtil alloc] init];
    [self.keyboardUtil setAnimateWhenKeyboardAppearAutomaticAnimBlock:^(ZYKeyboardUtil *keyboardUtil) {
        [keyboardUtil adaptiveViewHandleWithController:weakSelf adaptiveView:weakSelf.safetyCodeTextField,weakSelf.passwardTextField,weakSelf.rePasswardTextField, nil];
    }];
    
    
    [self initiateTimer];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf.view endEditing:YES];
    }];
    [self.view addGestureRecognizer:tap];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged) name:UITextFieldTextDidChangeNotification object:self.safetyCodeTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged) name:UITextFieldTextDidChangeNotification object:self.passwardTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged) name:UITextFieldTextDidChangeNotification object:self.rePasswardTextField];
}

- (void)initiateTimer {
    //获取到当前时间
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSDate *registerDate = [NSDate date];
    [user setValue:registerDate forKey:@"kauthtime"];
    [user synchronize];
    self.timer = [[NSTimer alloc] init];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(freshGetCode:)
                                                userInfo:nil
                                                 repeats:YES];
}

- (void)textFieldTextChanged {
    self.finishButton.enabled = (_safetyCodeTextField.text.length>0 && _passwardTextField.text.length == self.rePasswardTextField.text.length && self.rePasswardTextField.text.length >= 6);
    [self setPasswordStatus];
}

- (void)setPasswordStatus {
    // 处理对勾状体
    if (self.passwardTextField.text.length >= 6) {
        if ([self validatePassword:self.passwardTextField.text]) {
            self.passwdStatusButton.enabled = YES;
        } else {
            self.passwdStatusButton.enabled = NO;
        }
    } else {
        self.passwdStatusButton.enabled = NO;
    }
    
    if (self.rePasswardTextField.text.length >= 6) {
        if ([self validatePassword:self.rePasswardTextField.text]) {
            self.repasswdStatusButton.enabled = YES;
        } else {
            self.repasswdStatusButton.enabled = NO;
        }
    } else {
        self.repasswdStatusButton.enabled = NO;
    }
}

- (BOOL)validatePassword:(NSString*)passWord {
    NSString*passWordRegex =@"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate*passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return[passWordPredicate evaluateWithObject:passWord];
}

#pragma mark - CustomDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - event response
- (void)finishButtonAction {
    if ([self validatePassword:self.passwardTextField.text]) {
        if ([self.passwardTextField.text isEqualToString:self.rePasswardTextField.text]) {
            [self getData];
        } else {
            [MBProgressHUD showError:@"请输入相同密码"];
        }
    } else {
        [MBProgressHUD showError:@"请输入6到16位数字或字母"];
    }
}

- (void)getIdentCode {
    self.timeLabel.userInteractionEnabled = NO;
    [self initiateTimer];
    NSDictionary *param = @{@"eId":self.parameterDictionary[@"eId"],
                            @"mobile":self.parameterDictionary[@"mobile"]};
    [[ICLoginNetworkManager sharedInstance] getIdentCode:param success:^(id object) {
        
    } failure:^(NSError *error) {
        
    }];
}

-(void)freshGetCode:(NSTimer *)timer{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSDate  *date = (NSDate *)[user valueForKey:@"kauthtime"];
    double time = [[NSDate date] timeIntervalSinceDate:date];
    int lastTime = 60 - time;
    self.timeLabel.text = [NSString stringWithFormat:@"(%d)秒后重新发送", lastTime];
    if (lastTime <= 0 ) {
        [self stopTimer];
        self.timeLabel.userInteractionEnabled = YES;
    } else {
        self.timeLabel.userInteractionEnabled = NO;
    }
}

//关闭倒计时
- (void)stopTimer {
    self.timeLabel.text = @"重新发送";
    [self.timer invalidate];
}

#pragma mark - private methods
- (void)setUI {
    CGFloat leftMargin = 15;
    CGFloat rightMargin= 15;
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
    }];
    
    self.topView.backgroundColor = [UIColor whiteColor];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo( self.topView.mas_bottom).offset(43);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.width.mas_equalTo(App_Frame_Width- leftMargin * 2);
    }];
    
    [self.phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(21);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.width.mas_equalTo(App_Frame_Width- leftMargin * 2);
    }];
    
    [self.safetyCodeTextField mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneLabel.mas_bottom).offset(56);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.width.mas_equalTo(App_Frame_Width / 3 * 2);
    }];
    
    [self.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.safetyCodeTextField.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-rightMargin);
    }];
    
    [self.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.safetyCodeTextField.mas_bottom).offset(12);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.right.equalTo(self.view.mas_right).offset(-rightMargin);
        make.height.mas_equalTo(0.5);
    }];
    
    [self.passwardTextField mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.safetyCodeTextField.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.width.mas_equalTo(App_Frame_Width / 3 * 2 + 30);
    }];
    
    [self.passwdStatusButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.passwardTextField.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-rightMargin);
    }];
    
    [self.bottomView_1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwardTextField.mas_bottom).offset(12);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.right.equalTo(self.view.mas_right).offset(-rightMargin);
        make.height.mas_equalTo(0.5);
    }];
    
    [self.rePasswardTextField mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwardTextField.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.width.mas_equalTo(App_Frame_Width / 3 * 2 + 30);
    }];
    
    [self.repasswdStatusButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.rePasswardTextField.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-rightMargin);
    }];
    
    [self.bottomView_2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.rePasswardTextField.mas_bottom).offset(12);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.right.equalTo(self.view.mas_right).offset(-rightMargin);
        make.height.mas_equalTo(0.5);
    }];
    
    [self.finishButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.rePasswardTextField.mas_bottom).offset(50);
        make.left.equalTo(self.view.mas_left).offset(leftMargin);
        make.width.mas_equalTo(App_Frame_Width - leftMargin * 2);
    }];
}

// 设置navigation
- (void)setNav {
    self.title = @"忘记密码";
}
// 网络请求
- (void)getData {
    // 发送新密码
    NSDictionary *param = @{@"eId":self.parameterDictionary[@"eId"],
                            @"identCode":self.safetyCodeTextField.text,
                            @"newPassword":self.passwardTextField.text};
    [[ICLoginNetworkManager sharedInstance] resetPassword:param success:^(id object) {
        [MBProgressHUD showSuccess:@"修改密码成功"];
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    } failure:^(NSError *error) {
        [MBProgressHUD showError:error.domain];
    }];
}

#pragma mark - getters and setters
-(UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.autoresizingMask = 0xFF;
        _scrollView.contentMode = UIViewContentModeCenter;
        _scrollView.contentSize = CGSizeMake(3 * CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
        self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.scrollView.frame), 0);
        self.scrollView.pagingEnabled = YES;
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, -1, App_Frame_Width, 1)];
        [self.scrollView addSubview:_topView];
    }
    return _topView;
}
-(UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:17];
        _titleLabel.textColor = ICTEXTCOLOR_T1;
        _titleLabel.text = @"我们已经将验证码发送到您的手机:";
        [self.scrollView addSubview:_titleLabel];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

-(UILabel *)phoneLabel {
    if (!_phoneLabel) {
        _phoneLabel = [[UILabel alloc] init];
        _phoneLabel.font = ICFont(30 * Level);
        _phoneLabel.textColor = ICTEXTCOLOR_T1;
        NSString *mobile = self.parameterDictionary[@"mobile"];
        NSString *string = [mobile stringByReplacingOccurrencesOfString:[mobile substringWithRange:NSMakeRange(3,4)]withString:@"****"];
        _phoneLabel.text = string;
        [self.scrollView addSubview:_phoneLabel];
        _phoneLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _phoneLabel;
}

-(UITextField *)safetyCodeTextField {
    if (!_safetyCodeTextField) {
        _safetyCodeTextField = [[UITextField alloc] init];
        _safetyCodeTextField.font = [UIFont systemFontOfSize:16];
        _safetyCodeTextField.textColor = ICTEXTCOLOR_T1;
        _safetyCodeTextField.textAlignment = NSTextAlignmentLeft;
        _safetyCodeTextField.keyboardType = UIKeyboardTypePhonePad;
        [self.scrollView addSubview:_safetyCodeTextField];
        _safetyCodeTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSForegroundColorAttributeName:ICRGB(0x676767),NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        
        _safetyCodeTextField.delegate = self;
    }
    return _safetyCodeTextField;
}

-(UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] init];
        _timeLabel.textColor = ICTEXTCOLOR_T2;
        _timeLabel.font = [UIFont systemFontOfSize:14];
        [self.scrollView addSubview:_timeLabel];
        WEAKSELF;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf getIdentCode];
        }];
        [_timeLabel addGestureRecognizer:tap];
    }
    return _timeLabel;
}

-(UITextField *)passwardTextField {
    if (!_passwardTextField) {
        _passwardTextField = [[UITextField alloc] init];
        _passwardTextField.font = [UIFont systemFontOfSize:16];
        _passwardTextField.textColor = ICTEXTCOLOR_T1;
        _passwardTextField.textAlignment = NSTextAlignmentLeft;
        _passwardTextField.keyboardType = UIKeyboardTypeASCIICapable;
        _passwardTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入新密码（6-16位数字或字母）" attributes:@{NSForegroundColorAttributeName:ICRGB(0x676767),NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        _passwardTextField.secureTextEntry = YES;
        _passwardTextField.delegate = self;
        [self.scrollView addSubview:_passwardTextField];
    }
    return _passwardTextField;
}

-(UITextField *)rePasswardTextField {
    if (!_rePasswardTextField) {
        _rePasswardTextField = [[UITextField alloc] init];
        _rePasswardTextField.font = [UIFont systemFontOfSize:16];
        _rePasswardTextField.textColor = ICTEXTCOLOR_T1;
        _rePasswardTextField.textAlignment = NSTextAlignmentLeft;
        _rePasswardTextField.keyboardType = UIKeyboardTypeASCIICapable;
        _rePasswardTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请再次输入新密码" attributes:@{NSForegroundColorAttributeName:ICRGB(0x676767),NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        
        _rePasswardTextField.secureTextEntry = YES;
        _rePasswardTextField.delegate = self;
        [self.scrollView addSubview:_rePasswardTextField];
    }
    return _rePasswardTextField;
}

-(UIButton *)finishButton {
    if (!_finishButton) {
        _finishButton = [[UIButton alloc] init];
        [_finishButton setTitle:@"完成" forState:UIControlStateNormal];
        [_finishButton addTarget:self action:@selector(finishButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_finishButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_detail_sender"] forState:UIControlStateNormal];
        [self.scrollView addSubview:_finishButton];
        _finishButton.enabled = NO;
    }
    return _finishButton;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        [self.scrollView addSubview:_bottomView];
        _bottomView.backgroundColor = ICRGB(0x9095a5);
    }
    return _bottomView;
}

-(UIView *)bottomView_1 {
    if (!_bottomView_1) {
        _bottomView_1 = [[UIView alloc] init];
        [self.scrollView addSubview:_bottomView_1];
        _bottomView_1.backgroundColor = ICRGB(0x9095a5);
    }
    return _bottomView_1;
}

-(UIView *)bottomView_2 {
    if (!_bottomView_2) {
        _bottomView_2 = [[UIView alloc] init];
        [self.scrollView addSubview:_bottomView_2];
        _bottomView_2.backgroundColor = ICRGB(0x9095a5);
    }
    return _bottomView_2;
}

-(UIButton *)passwdStatusButton {
    if (!_passwdStatusButton) {
        _passwdStatusButton = [[UIButton alloc] init];
        [_passwdStatusButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_rest_enabled"] forState:UIControlStateNormal];
        [_passwdStatusButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_rest_disabled"] forState:UIControlStateDisabled];
        [self.scrollView addSubview:_passwdStatusButton];
        _passwdStatusButton.enabled = NO;
    }
    return _passwdStatusButton;
}
-(UIButton *)repasswdStatusButton {
    if (!_repasswdStatusButton) {
        _repasswdStatusButton = [[UIButton alloc] init];
        [_repasswdStatusButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_rest_enabled"] forState:UIControlStateNormal];
        [_repasswdStatusButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_rest_disabled"] forState:UIControlStateDisabled];
        [self.scrollView addSubview:_repasswdStatusButton];
        _repasswdStatusButton.enabled = NO;
    }
    return _repasswdStatusButton;
}

-(void)dealloc {
    self.timer = nil;
}
@end
